package io.github.zhibaibubai.blog;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;


public class MyDBUtil {
    private static Connection connection;

    public synchronized static Connection getConnection() {
        if (connection != null) {
            return connection;
        }

        try {
            // 读取配置文件
            Properties properties = new Properties();
            InputStream inputStream = MyDBUtil.class.getClassLoader().getResourceAsStream("application.properties");
            if (inputStream == null) {
                throw new RuntimeException("配置文件未找到！");
            }
            properties.load(inputStream);

            String url = properties.getProperty("db.url");
            String username = properties.getProperty("db.username");
            String password = properties.getProperty("db.password");
            String driver = properties.getProperty("db.driver");

            // 加载数据库驱动
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
            System.out.println("Connected to database");
        } catch (IOException | ClassNotFoundException | RuntimeException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException("数据库连接失败", e);
        }

        return connection;
    }
}